<template>
  <div class="app-container">
    <el-form ref="placeCodeForm" v-loading="formLoading" :rules="rules" :model="form" label-position="top">
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="培训类别" prop="typeId" style="width: 200px">
            <el-cascader v-model="form.typeId" placeholder="请选择培训类别"
                         :options="typeList"
                         :show-all-levels="false"
                         :props="{value:'id',label:'name'}"
                         filterable
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="培训专业" prop="configId" style="width: 200px">
            <el-cascader v-model="form.configId" placeholder="请选择培训专业"
                         :options="specialityList"
                         :show-all-levels="false"
                         :props="{value:'id',label:'name'}"
                         filterable
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="培训人数" prop="number" style="width: 200px">
            <el-input v-model="form.number" placeholder="请输入培训人数" clearable/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="专业介绍" prop="Abstract">
            <div class="container">
              <Toolbar :editor="editor" :default-config="toolbarConfig" :mode="mode"/>
              <Editor v-model="form.introduce" :default-config="editorConfig" :mode="mode" @onCreated="onCreated"/>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  editSpecialityApi,
  getQuestionnaireConfigApi,
  getSpecialityByIdApi,
} from '@/api/trainCode'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

export default {
  components: {Editor, Toolbar},
  name: 'PlaceCodeDetail',
  data() {
    return {
      editor: null,
      category: [],
      //期望职位级联选择器配置
      optionProps: {
        value: 'id',
        label: 'jobTitle',
        children: 'subLevelModelList',
        multiple: true
      },
      typeList: [],
      specialityList: [],
      toolbarConfig: {
        excludeKeys: [
          // 排除菜单组，写菜单组 key 的值即可
          'group-video' // 去掉视频
        ]
      },
      editorConfig: {MENU_CONF: {}, placeholder: ''},
      mode: 'default',
      uploadUrl: process.env.VUE_APP_UPLOAD_API,
      dialogImageUrl: '',
      dialogVisible: false,
      form: {
        id: null,
        typeId: '',
        trainId: '',
        configId: '',
        number: '',
        introduce: '',
      },
      rules: {
        typeId: [{required: true, trigger: 'blur', message: '请选择培训类别'}],
        configId: [{required: true, trigger: 'blur', message: '请选择专业'}],
        number: [{required: true, trigger: 'blur', message: '请输入专业人数'}],
        introduce: [{required: true, trigger: 'blur', message: '请输入培训介绍'}],
      },
      formLoading: false,
    }
  },
  props: ['id', 'closeDialog','trainId'],
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    handleAvatarSuccess(res, file) {
      this.form.imaUrl = res.imgURL;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },

    submit() {
      this.$refs.placeCodeForm.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            text: '提交中'
          })
          if (this.form.id == null) {
            this.form.id = 0;
          }
          const form = JSON.parse(JSON.stringify(this.form));
          console.log(form)
          if(this.form.typeId.length === 1)
          {
            form.typeId = this.form.typeId[0]
          }
          if(this.form.configId.length === 1)
          {
            form.configId = this.form.configId[0]
          }
          form.trainId = this.trainId

          editSpecialityApi(form).then((res) => {
            this.$message.success('保存成功');
            this.closeDialog(0);
          }).catch(() => {
            this.$message.error('保存失败');
          }).finally(() => {
            loading.close();
          })
        } else {
          return false
        }
      })
    },

    getDetail() {
      this.formLoading = true;
      getSpecialityByIdApi({id: this.id}).then((res) => {
        this.form.typeId = parseInt(res.typeId);
        console.log(this.form.typeId)
        this.form.trainId = parseInt(res.trainId);
        this.form.id = res.id;
        this.form.configId = parseInt(res.configId);
        this.form.number = parseInt(res.number);;
        this.form.introduce = res.introduce;
      }).finally(() => {
        this.formLoading = false;
      })
    },
    getTypeList()
    {
      getQuestionnaireConfigApi({type: 7}).then((res) => {
        this.typeList = res;
      }).finally(() => {
        this.formLoading = false;
      })
      getQuestionnaireConfigApi({type: 5}).then((res) => {
        this.specialityList = res;
      }).finally(() => {
        this.formLoading = false;
      })
    },
  },
  mounted() {
    this.getTypeList()
    if (this.id) {
      this.getDetail();
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  created() {
    this.editorConfig.placeholder = '请输入使用说明内容...'
    this.editorConfig.MENU_CONF['uploadImage'] = {
      timeout: 5 * 1000, // 5s
      fieldName: 'image',
      // 用户自定义上传图片
      customUpload(file, insertFn) {
        var axios = require('axios')
        var FormData = require('form-data')
        var data = new FormData()
        data.append('file', file) // file 即选中的文件
        var config = {
          method: 'post',
          url: process.env.VUE_APP_UPLOAD_API, // 上传图片地址
          data: data
        }
        axios(config)
          .then(function (res) {
            const url = res.data.imgURL // 拼接成可浏览的图片地址
            insertFn(url, '使用说明', url) // 插入图片
          })
          .catch((res) => {
            console.log(res)
          })
      }
    }
  },
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}
</style>
<style scoped>
/*
*让select撑开
*/
.el-select, .el-cascader {
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
